#!groovy
import groovy.json.JsonOutput
import groovy.json.JsonSlurper



node (params.nodeLabel) {
    def status = 0
    def tomcatHome = '/home/tomcat'
    def tomcatWebPath = tomcatHome + '/webapps'
    def bakPath = '/opt/app-bak'
    println(params.action)
    if('stop' == params.action){
        actionStopTomcat()
    }else {
        println('No Action Not Found...')
    }
}

def notifyDeployCentral(status){
    stage("Notify DeployCentral"){
        echo "Notify DeployCentral: "+status
        def response = httpRequest(url:"${params.callBackHost}/deploy-central/prod/jenkins/notify?callBackId=${params.callBackId}&status=${status}&buildId=${BUILD_ID}&action=${JOB_NAME}@${params.nodeLabel}",timeout: 10)
        println('Status: '+response.status)
    }
}


def stopTomcat(){
    println("---- Stop Tomcat ----")
    def pid = sh(script: 'ps -ef | grep -w tomcat | grep -v grep | awk \'{print $2}\'',returnStdout: true).trim()
    echo 'Tomcat pid: '+ pid
    if(null != pid && "" != pid){
        sh "kill ${pid}"
    }
    sleep 5
}

def actionStopTomcat(){
    stage('Stop App'){
        try{
            stopTomcat()
            notifyDeployCentral(16001)
        }catch (e){
            echo 'Stop App Error !'
            notifyDeployCentral(16002)
            throw e
        }
    }
}